package com.openatc.optimize.fixedtimeplan.config.cross;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author mz
 * @version 1.0
 * @date 2021/12/6 15:37
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BarrierItem {
    private int ring;
    private List<Integer> data;
    private boolean adjusted = false;
    private long duration;
    public long calcDuration(Map<Integer, Phase> phaseMap){
        long tempduration = 0;
        for(int id:data){
            tempduration += phaseMap.get(id).getDuration();
        }
        return tempduration;
    }

    public void adjustPhaseDuration(Map<Integer, Phase> phaseMap, long duration){
        this.duration = duration;
        double totalsplitratio = 0;
        for(int id:data){
            totalsplitratio += phaseMap.get(id).getSplitratio();
        }


        long temptotalduration = 0;
        for(int i=0;i<data.size();i++){
            int id = data.get(i);
            if(i != data.size() - 1){
                phaseMap.get(id).setDuration(Math.round(duration * phaseMap.get(id).getSplitratio() / totalsplitratio));
                temptotalduration += phaseMap.get(id).getDuration();
            }else {
                phaseMap.get(id).setDuration(duration - temptotalduration);
            }

        }
    }

    public static BarrierItem createBarrierItemByBarrierItemFeature(BarrierItemFeature barrierItemFeature){

        List<Integer> data = new LinkedList<>();
        for(int phaseid:barrierItemFeature.getData()){
            data.add(phaseid);
        }
        return BarrierItem.builder().data(data).ring(barrierItemFeature.getRing()).build();
    }
}
